var urlPrefix = "https://bird.ioliu.cn/v1?url=",
	rootPath = "http://app.xiaoweicanting.com/",
	uploadUrl = "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=updateEquipmentInfoById";
	
function EquipmentImagesList(element, num, prefix, maxSize) {
	this.imageIndex = 0;
	this.imageListNum = num;
	this.localImageFiles = [];
	this.remoteImageFiles = [];
	this.imageSize = 0;
	this.element = element;
	
	EquipmentImagesList.prototype.listCount++;
	this.prefix = prefix || ("list" + this.listCount + "-image-");
	this.maxSize = maxSize || 10 * 1024 * 1024;
}


EquipmentImagesList.prototype.listCount = 0;
EquipmentImagesList.prototype.init = function() {
	this.imageIndex = this.element.querySelectorAll(".image-item").length;
	var that = this,
		slice = [].slice;
	// 初始化删除按钮
	slice.call(this.element.querySelectorAll(".image-close")).forEach(function(v) {
		v.addEventListener("tap", function() {
			that.removeImageFile(this.parentNode.getAttribute("data-index"), false);
		}, false);
	});
	
	// 初始化that.remoteImageFiles
	slice.call(this.element.querySelectorAll(".image-item")).forEach(function(v) {
		var imgPath = v.querySelector("img").src;
		that.addImageFile(false, {
			index: v.getAttribute("data-index"),
			path: imgPath,
			size: 0
		});
	});
	
	this.element.querySelector(".image-add").addEventListener("tap", function() {
		var btnArray = [{
				title: "拍照"
			}, {
				title: "从相册选择"
			}];
		plus.nativeUI.actionSheet({
			title: "选择照片",
			cancel: "取消",
			buttons: btnArray
		}, function(e) {
			var choosen = e.index;
			
			switch(choosen) {
				case 0:
					// 用户点击取消按钮
					break;
				
				case 1:
					// 用户点击拍照按钮
					var cmr = plus.camera.getCamera();
					cmr.captureImage(function(imagePath) {
						var name = imagePath.substr(imagePath.lastIndexOf("/") + 1);
						
						plus.zip.compressImage({
							src: imagePath,
							dst: "_doc/" + name,
							overwrite: true,
							quality: 50
						}, function(zip) {
							
							that.imageSize += zip.size;
							if(that.imageSize > that.maxSize)
								return mui.toast("图片总大小已超出10Mb，请重新选择~");
							that.newPlaceholder(zip.target);

							that.addImageFile(true, {
								index: that.imageIndex,
								path: zip.target,
								size: zip.size
							});
//							result = "";
//							for(var i = 0, len = that.imageFiles.length; i < len; i++) {
//								result += that.imageFiles[i].name + " ";
//							}
//							alert(result);
						}, function(zip) {
							mui.toast("图片压缩失败~");
						});
					});
					break;
					
				case 2:
					plus.gallery.pick(function(imagePath) {
						var name = imagePath.substr(imagePath.lastIndexOf('/') + 1);
						plus.zip.compressImage({
							src: imagePath,
							dst: '_doc/' + name,
							overwrite: true,
							quality: 50
						}, function(zip) {
							that.imageSize += zip.size;
							if(that.imageSize > that.maxSize)
								return mui.toast("图片总大小已超出10Mb，请重新选择~");
							
							that.newPlaceholder(zip.target);
							alert(zip.target);
							that.addImageFile(true, {
								index: that.imageIndex,
								path: zip.target,
								size: zip.size
							});
//							result = "";
//							for(var i = 0, len = that.imageFiles.length; i < len; i++) {
//								result += that.imageFiles[i].name + " ";
//							}
//							alert(result);
						}, function(zipe) {
							mui.toast('图片压缩失败~');
						});
					});
			}
		})
	}, false);
};

EquipmentImagesList.prototype.newPlaceholder = function(imagePath) {
	var that = this;
	
	var imageItem = document.createElement("div");
	imageItem.className = "image-item";
	imageItem.id = this.prefix + (++this.imageIndex);
	imageItem.setAttribute("data-index", this.imageIndex);
	
	var imageClose = document.createElement("div");
	imageClose.classList.add("image-close");
	imageClose.innerHTML = "X";
	
	var img = document.createElement("img");
	img.src = imagePath;
	img.setAttribute("data-preview-src", "");
	img.setAttribute("data-preview-group", this.imageListNum);
	
	imageClose.addEventListener("tap", function() {
		that.removeImageFile(this.parentNode.getAttribute("data-index"), true);
	}, false);
	
	imageItem.appendChild(imageClose);
	imageItem.appendChild(img);
	this.element.insertBefore(imageItem, this.element.querySelector(".image-add"));
	
	mui.previewImage();
};

EquipmentImagesList.prototype.addImageFile = function(local, info) {
	var files = local ? this.localImageFiles : this.remoteImageFiles;
	files.push({
		name: "image" + info.index,
		path: info.path,
		size: info.size
	});
	this.imageSize += info.size;
};

EquipmentImagesList.prototype.removeImageFile = function(imageIndex, removeLocal) {
	var files = removeLocal ? this.localImageFiles : this.remoteImageFiles,
		ret;
	for(var i = 0, len = files.length; i < len; i++) {
		if(files[i].name === "image" + imageIndex) {
			var item = document.getElementById(this.prefix + imageIndex);
			item.parentNode.removeChild(item);
			
			ret = files.splice(i, 1);
			this.imageSize -= ret[0].size;
			return ret;
		}
	}
};
mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getEquipmentInfoById&hospitalid=10&departmentid=11&uid=3&token=dfaf&id=13", {
	type: "GET",
	dataType: "json",
	async: true,
	success: function(data, textStatus) {
		if(textStatus === "success") {
			var data = data.data,
				headImage = document.getElementById("head-image"),
				headText = document.getElementById("head-text"),
				form = document.forms[0];
			headImage.style.backgroundImage = "url(" + rootPath + data.pics[0] + ")";
			headText.innerHTML = "<li>" + data.name + "</li><li>编号：" + data.assetsid + "</li><li>状态：" + data.stateDesc + "</li>";
			form.innerHTML = '<input type="hidden" name="id" value="' + data.eid + '">' + 
							 '<input type="hidden" name="hospitalid" value="' + data.hospitalid + '">' + 
							 '<input type="hidden" id="department-id" name="departmentid" value="' + data.departmentid + '">' + 
							 '<input type="hidden" id="inchargeuid" name="inchargeuid" value="' + data.inchargeuid + '">' + 
							 '<input type="hidden" id="inchargeuname" name="inchargeuname" value="' + data.inchargeuname + '">' + 
							 '<input type="hidden" id="modelname-id" name="modelid" value="' + data.modelid + '">' + 
							 '<input type="hidden" id="specname-id" name="specid" value="' + data.specid + '">' + 
								'<h2>归属信息</h2>' +
								'<div class="mui-input-row">' + 
									'<label>医院</label>' + 
									'<a href="#" class="mui-btn-outlined" name="hospitalname" id="link-to-hospital">' + data.hospitalname + '</a>' +
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>科室</label>' + 
									'<a href="#department" class="mui-btn-outlined" name="departmentname" id="link-to-department">' + data.departmentname + '</a>' + 
								'</div>' + 
								'<div class="mui-input-row" id="doctor-info">' + 
									'<label>' + 
										'<span class="doctor-display" style="background-image: url(' + rootPath + data.inchargeuimg + ');"></span>' +
										'<span class="doctor-name">' + data.adduname + '</span>' + 
									'</label>' +
									'<a href="#inchargeurole-name" class="mui-btn-outlined" name="inchargeurole_name" id="link-to-inchargeurole-name">' + data.inchargeurole_name + '</a>' + 
								'</div>' + 
								'<h2>基础信息</h2>' + 
								'<div class="mui-input-row">' + 
									'<label>设备类型</label>' + 
									'<a href="#equipment-modelname" class="mui-btn-outlined" name="modelname" id="link-to-equipment-modelname">' + data.modelname + '</a>' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>设备型号</label>' + 
									'<a href="#equipment-specname" class="mui-btn-outlined" name="specname" id="link-to-equipment-specname">' + data.specname + '</a>' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>设备厂家</label>' + 
									'<input type="text" name="baseManufactory" class="mui-input-clear" value="' + data.baseManufactory + '" >' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>设备产地</label>' + 
									'<input type="text" name="baseManufactoryBase" class="mui-input-clear" value="' + data.baseManufactoryBase + '" >' + 
								'</div>' + 
								'<div class="mui-input-row" id="equipment-desc">' + 
									'<label>设备描述</label>' + 
									'<textarea id="textarea" rows="3" name="baseIntro">' + data.baseIntro + '</textarea>' + 
								'</div>' + 
								renderImages(data.basePics, 1) + 
								'<h2>个性信息</h2>' + 
								'<div class="mui-input-row">' + 
									'<label>设备名称</label>' + 
									'<input type="text" class="mui-input-clear" name="name" value="' + data.name + '">' + 
								'</div>' + 
								'<div class="mui-input-row" id="qrcode-field">' + 
									'<label>设备二维码</label>' + 
									'<img id="qrcode" src="' + rootPath + data.qrCode + '" data-preview-src="" data-preview-group="3" />' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>服务厂家</label>' + 
									'<input type="text" class="mui-input-clear" name="serviceSupplier" value="' + data.serviceSupplier + '">' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>出厂日期</label>' + 
									'<a id="pickDateBtn" href="#" name="productiondate">' + data.productiondate + '</a>' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>资产编号</label>' + 
									'<input type="text" class="mui-input-clear" name="assetsid" value="' + data.assetsid + '">' + 
								'</div>' + 
								'<div class="mui-input-row">' + 
									'<label>出厂编号</label>' + 
									'<input type="text" class="mui-input-clear" name="factorySalesCode" value="' + data.factorySalesCode + '">' + 
								'</div>' + 
								'<div class="mui-input-row" id="equipment-desc">' + 
									'<label>设备描述</label>' + 
									'<textarea id="textarea" rows="3" name="intro">' + data.intro + '</textarea>' + 
								'</div>' + 
								renderImages(data.pics, 2) + 
								'<input type="submit" id="save-btn" value="保 存" />';
			mui.previewImage();
			
			fetchDepartmentList();
			
			fetchDoctorList(data.departmentid);
			
			fetchModelNameList(data.departmentid);
			
			fetchSpecNameList(data.departmentid, data.modelid);
	      	
	      	var pickDateBtn = document.getElementById("pickDateBtn");
			pickDateBtn.addEventListener('tap', function() {
				var productiondate = data.productiondate.split("-"),
					date = new Date();
				date.setFullYear(productiondate[0], parseInt(productiondate[1]) - 1, parseInt(productiondate[2]));
				var minDate = new Date();
				minDate.setFullYear(2010, 0, 1);
				var maxDate = new Date();
				maxDate.setFullYear(2020, 11, 31);
				plus.nativeUI.pickDate(function(e) {
					var d = e.date,
						month = d.getMonth() + 1,
						day = d.getDate();
					pickDateBtn.innerText = d.getFullYear() + "-" + (month > 9 ? month : "0" + month) + "-" + (day > 9 ? day : "0" + day);
				}, function(e) {
					pickDateBtn.innerText = "您没有选择日期";
				}, {
					title: "请选择日期",
					date: date,
					minDate: minDate,
					maxDate: maxDate
				});
			});
			
			mui.plusReady(function() {
				var list1 = new EquipmentImagesList(document.getElementById("image-list-1"), 1);
				list1.init();
				
				var list2 = new EquipmentImagesList(document.getElementById("image-list-2"), 2);
				list2.init();
				
				mui.previewImage();
				
				document.getElementById("save-btn").addEventListener("tap", function() {
					var uploader = plus.uploader.createUpload(uploadUrl, {
						method: "POST"
					}, function(upload, status) {
						alert(upload.responseText);
						if(status == 200) {
							mui.toast("保存成功！");
						} else {
							mui.toast("修改失败！");
						}
					}),
						slice = [].slice,
						input = slice.call(form.querySelectorAll("input, textarea")),
						links = slice.call(form.querySelectorAll("a"));
					input.forEach(function(v) {
						if(v.type === "submit") return;
						uploader.addData(v.name, v.value);
					});
					links.forEach(function(v) {
						uploader.addData(v.name, v.innerHTML);
					});
					
					
					
					uploadImages(uploader, list1, "basepics");
					uploadImages(uploader, list2, "pics");
					
					uploader.start();
				}, false);
			});
		}
	}
});

function fetchDepartmentList() {
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getNewEquipmentHallList&hospitalid=10&uid=3&token=dfaf", {
		type: "GET",
		dataType: "json",
		async: true,
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var departmentList = document.getElementById("department-list"),
					data = data.data,
					slice = [].slice,
					dlHtml = "";
				for (var i = 0, departmentListLength = data.length; i < departmentListLength; i++) {
					dlHtml += '<li class="mui-table-view-cell"><a href="#" class="mui-navigate-right" data-department-id="' + data[i].hid + '">' + data[i].hallname + '</a></li>';
				}
				departmentList.innerHTML = dlHtml;
				slice.call(departmentList.querySelectorAll("a")).forEach(function(v) {
					v.addEventListener("tap", function() {
						document.getElementById("department").style.display = "none";
						document.querySelector(".mui-backdrop").style.display = "none";
						
						var departmentId = this.getAttribute("data-department-id");
						document.getElementById("department-id").value = departmentId;
						document.getElementById("link-to-department").innerHTML = this.innerHTML;
						
						// 根据用户选择的科室拉取科室医生列表信息
						fetchDoctorList(departmentId);
						
						// 拉取设备类型信息
						fetchModelNameList(departmentId);
						
						// 拉取设备型号信息
						fetchSpecNameList(departmentId, document.getElementById("link-to-equipment-modelname").innerHTML);
					}, false);
				})
			}
		}
	});
}

function fetchDoctorList(departmentid) {
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getNewEquipmentHallDocterList&hospitalid=10&departmentid=" + departmentid + "&uid=3&token=dfaf", {
		type: "GET",
		dataType: "json",
		async: true,
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					doctorListLength = data.length,
					doctorList = document.getElementById("inchargeurole-name-list"),
					slice = [].slice,
					form = document.forms[0],
					doctorListHtml = "";
				for (var i = 0; i < doctorListLength; i++) {
					doctorListHtml += '<li class="mui-table-view-cell"><a href="#" class="mui-navigate-right" data-role-name="' + data[i].role_name + '" data-doctor-display="' + data[i].headimg + '" data-doctor-uid="' + data[i].eid + '">' + data[i].username + '</a></li>';
				}
				if(doctorListLength === 0) doctorListHtml = '<li><p style="color: #999;text-align: center;line-height: 40px; font-size: 18px;">暂无可选项</p></li>';
				doctorList.innerHTML = doctorListHtml;
				
				slice.call(doctorList.querySelectorAll("a")).forEach(function(v) {
					v.addEventListener("tap", function() {
						document.getElementById("inchargeurole-name").style.display = "none";
						document.querySelector(".mui-backdrop").style.display = "none";
						
						document.getElementById("inchargeuid").value = this.getAttribute("data-doctor-uid");
						document.getElementById("inchargeuname").value = this.innerHTML;
						
						var doctorDisplay = this.getAttribute("data-doctor-display"),
							element = form.querySelector(".doctor-display");
						if(doctorDisplay) {
							element.innerHTML = "";
							element.style.backgroundImage = "url(" + doctorDisplay +")";
						} else {
							element.style.backgroundImage = "none";
							element.innerHTML = this.innerHTML.slice(0, 1).toUpperCase();
						}
						form.querySelector(".doctor-name").innerHTML = this.innerHTML;
						document.getElementById("link-to-inchargeurole-name").innerHTML = this.getAttribute('data-role-name');
					}, false);
				});
			}
		}
	});
}

function fetchModelNameList(departmentid) {
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getNewEquipmentTypeList&hospitalid=10&departmentid=" + departmentid + "&uid=3&token=dfaf", {
		type: "GET",
		dataType: "json",
		async: true,
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					modelNameList = document.getElementById("equipment-modelname-list"),
					modelNameCount = data.length,
					slice = [].slice,
					modelNameHtml = "";
					
				for (var i = 0; i < modelNameCount; i++) {
					modelNameHtml += '<li class="mui-table-view-cell"><a href="#" class="mui-navigate-right" data-type-id="' + data[i].typeid + '">' + data[i].name + '</a></li>';
				}
				if(modelNameCount === 0) modelNameHtml = '<li><p style="color: #999;text-align: center;line-height: 40px; font-size: 18px;">暂无可选项</p></li>';
				modelNameList.innerHTML = modelNameHtml;
				slice.call(modelNameList.querySelectorAll("a")).forEach(function(v) {
					v.addEventListener("tap", function() {
						document.getElementById("equipment-modelname").style.display = "none";
						document.querySelector(".mui-backdrop").style.display = "none";
						
						var typeid = this.getAttribute("data-type-id");
						document.getElementById("modelname-id").value = typeid;
						document.getElementById("link-to-equipment-modelname").innerHTML = this.innerHTML;
						
						fetchSpecNameList(departmentid, typeid);
					}, false);
				})
			}
		}
	});
}

function fetchSpecNameList(departmentid, typeid) {
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getNewEquipmentSpecList&hospitalid=10&departmentid=" + departmentid + "&uid=3&typeid=" + typeid + "&token=dfaf", {
		type: "GET",
		dataType: "json",
		async: true,
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					specNameList = document.getElementById("equipment-specname-list"),
					specNameCount = data.length,
					slice = [].slice,
					specNameHtml = "";
					
				for (var i = 0; i < specNameCount; i++) {
					specNameHtml += '<li class="mui-table-view-cell"><a href="#" class="mui-navigate-right" data-spec-id="' + data[i].specid + '">' + data[i].name + '</a></li>';
				}
				if(specNameCount === 0) specNameHtml = '<li><p style="color: #999;text-align: center;line-height: 40px; font-size: 18px;">暂无可选项</p></li>';
				specNameList.innerHTML = specNameHtml;
				slice.call(specNameList.querySelectorAll("a")).forEach(function(v) {
					v.addEventListener("tap", function() {
						document.getElementById("equipment-specname").style.display = "none";
						document.querySelector(".mui-backdrop").style.display = "none";
						
						document.getElementById("specname-id").value = this.getAttribute("data-spec-id");
						document.getElementById("link-to-equipment-specname").innerHTML = this.innerHTML;
					}, false);
				})
			}
		}
	});
}

function renderImages(data, imageListNum) {
	var html = '<div class="mui-input-row"><label>设备图片</label><div class="equipment-images" id="image-list-' + imageListNum + '">',
		len = data.length;
	for(var i = 1; i <= len; i++) {
		html += '<div class="image-item" id="list'+ imageListNum +'-image-' + i + '" data-index="' + i + '">' + 
					'<div class="image-close">X</div>' + 
					'<img src="' + rootPath + data[i - 1] + '" data-preview-src="" data-preview-group="' + imageListNum + '" />' + 
				'</div>';
	}
	html += '<div class="image-add">+</div></div></div>';	
	return html;
}

function uploadImages(uploader, imageList, field) {
	imageList.localImageFiles.forEach(function(v) {
		uploader.addFile(v.path, {
			key: field + "-" + v.name
		});
	});
	
	var remoteImageFiles = [];
	imageList.remoteImageFiles.forEach(function(v) {
		remoteImageFiles.push(v.path);
	});
	uploader.addData(field, JSON.stringify(remoteImageFiles));
}
